package com.sunspring.zdcall.util;

import com.google.common.collect.Lists;
import com.sunspring.zdcall.common.constant.enums.DatasourceEnum;
import com.sunspring.zdcall.entity.ZdConfigDatasource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.List;

/**
 * jdbc获取所有db数据源
 * @author wulei
 * @date 2018-12-25
 **/
@Slf4j
public class JdbcUtil {

    private final static String URL = "jdbc:sqlserver://192.168.0.222:1433;DatabaseName=zd_v2.0";

    private final static String USERNAME = "sa";

    private final static String PASSWORD = "pacs.123";


    static {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有的db流数据源
     * @return List<ZdConfigDatasource>
     */
    public static List<ZdConfigDatasource> getDbDatasource() {
        List<ZdConfigDatasource> datasourceList = Lists.newArrayList();
        try {
            Connection connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
            Statement statement = connection.createStatement();
            String sql = "SELECT\n" +
                    "datasource_id,\n" +
                    "source_type,\n" +
                    "source_url,\n" +
                    "username,\n" +
                    "password,\n" +
                    "db_type\n" +
                    "FROM\n" +
                    "\n" +
                    "ZD_config_datasource\n";
            ResultSet resultSet = statement.executeQuery(sql);

            while(resultSet.next()) {
                int sourceType = resultSet.getInt("source_type");
                if (sourceType != DatasourceEnum.db.getCode()) {
                    continue;
                }
                int id = resultSet.getInt("datasource_id");
                String url = resultSet.getString("source_url");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                int dbType = resultSet.getInt("db_type");
                ZdConfigDatasource datasource = new ZdConfigDatasource(id,url,username,password,dbType);
                datasourceList.add(datasource);
            }
            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            log.error("jdbcUtil异常" + e);
        }
        return datasourceList;
    }


}
